# -*- encoding: utf-8 -*-
"""

PyCharm 低通滤波器实践01
2024年10月23日16时44分
by wenyang

文件主要内容:


"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, filtfilt

def main():


    # 生成示例信号
    fs = 100  # 采样频率
    T = 5.0  # 采样时间
    t = np.linspace(0, T, int(T * fs), endpoint=False)  # 时间变量
    # 创建一个信号：包含40Hz和5Hz的正弦波
    signal = np.sin(2 * np.pi * 40 * t) + 0.5 * np.sin(2 * np.pi * 5 * t)

    # 设计低通滤波器
    def butter_lowpass(cutoff, fs, order=5):
        nyq = 0.5 * fs  # 奈奎斯特频率
        normal_cutoff = cutoff / nyq  # 归一化截止频率
        b, a = butter(order, normal_cutoff, btype='low', analog=False)
        return b, a

    def lowpass_filter(data, cutoff, fs, order=5):
        b, a = butter_lowpass(cutoff, fs, order=order)
        y = filtfilt(b, a, data)  # 双向滤波
        return y

    # 应用低通滤波器
    cutoff = 10  # 截止频率
    filtered_signal = lowpass_filter(signal, cutoff, fs)

    # 绘制结果
    plt.figure(figsize=(10, 6))
    plt.subplot(2, 1, 1)
    plt.plot(t, signal, label='original signal')
    plt.title('original signal and filtered signal')
    plt.xlabel('time [s]')
    plt.ylabel('amplitude')
    plt.legend()

    plt.subplot(2, 1, 2)
    plt.plot(t, filtered_signal, label='filtered signal', color='orange')
    plt.xlabel('time [s]')
    plt.ylabel('amplitude')
    plt.legend()

    plt.tight_layout()
    plt.show()


if __name__ == "__main__":
    main()
